<?php
//多线程抓取远程文件类
class Http
{
  //opt参数
  public $opt = array();

  //保存目录,如果为空则不保存
  public $saveDir = ''; //示例：Public/images/thumb/
  public $imgWidth = 5000;
  public $imgHeight = 5000;

  /**
  * curl 多线程
  *
  * @param array $array 并行网址
    * @param int $timeout 超时时间
  * @return mix
  */
  public function curl_http($array, $timeout=150){
    $responses = $map = array();

    $queue = curl_multi_init();//创建多个curl语柄
    foreach($array as $k=>$url){
      
      $ch  = curl_init();//初始化

      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);//设置超时时间
      curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
      curl_setopt($ch, CURLOPT_MAXREDIRS, 7);//HTTp定向级别 ，7最高
      curl_setopt($ch, CURLOPT_HEADER, false);//这里不要header，加块效率
      curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // 302 redirect
      curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);//要求结果为字符串且输出到屏幕上
      curl_setopt($ch, CURLOPT_HTTPGET, true);
      foreach ($this->opt as $key => $value) {
        curl_setopt($ch, $key, $value);
      }
      if(stristr($url, 'mangafiles.com')) {
        curl_setopt($ch, CURLOPT_REFERER, 'http://www.manhuadao.com/book/jinjidejuren/');
      }
      elseif(!isset($this->opt[CURLOPT_REFERER])) {
        curl_setopt($ch, CURLOPT_REFERER, $url);
      }

      curl_multi_add_handle ($queue,$ch);
      $map[(string) $ch] = $url;
    }

    do {
      while (($code = curl_multi_exec($queue, $active)) == CURLM_CALL_MULTI_PERFORM) ;

      if ($code != CURLM_OK) { break; }

      // a request was just completed -- find out which one
      while ($done = curl_multi_info_read($queue)) {

        // get the info and content returned on the request
        $info = curl_getinfo($done['handle']);
        $error = curl_error($done['handle']);
        $results = curl_multi_getcontent($done['handle']);

        //save
        $responses[$map[(string) $done['handle']]] = compact('info', 'error', 'results');

        // remove the curl handle that just completed
        curl_multi_remove_handle($queue, $done['handle']);
        curl_close($done['handle']);
      }

      // Block for data in / output; error handling is done by curl_multi_exec
      if ($active > 0) {
        curl_multi_select($queue, 0.5);
      }

    } while ($active);

    curl_multi_close($queue);
    return $responses;
  }

}
?>